
import java.awt.Canvas;
import java.awt.image.BufferStrategy;

/*	This thread was based on the tutorials on http://obviam.net/index.php/table-of-contents/
 * 
 */

public class GameThread extends Thread 
{
	Game panel;
	public boolean running;
	
	private final static int FPS = 90;
	private final static int TIME_PER_FRAME = 1000 / FPS;
	private final static int MAX_FRAME_SKIPS = 5;

	
	private long framesPerStatInterval = 0;
	private long intervalTimer = 0l;
	private long lastTime = 0l;
	private final static int STAT_PERIOD = 1000;

	
	public GameThread(Game canvas)
	{
		this.panel = canvas;
		running = true;
	}

	public void setRunning(boolean running)
	{
		this.running = running;
	}
	
	public void run()
	{
		Long tickCount = 0L;
		
		long beginTime;
		long timeDiff;
		int sleepTime = 0;
		int framesSkipped = 0;
		while (running)
		{
			try 
			{
				synchronized(panel)
				{
					beginTime = System.currentTimeMillis();
					panel.update(System.currentTimeMillis());
					panel.draw();	
					timeDiff = System.currentTimeMillis() - beginTime;
					
					sleepTime = (int) (TIME_PER_FRAME - timeDiff);
					if (sleepTime > 0)
					{
						try 
						{
							Thread.sleep(sleepTime);
						} 
						catch(InterruptedException e)
						{
						}
					}
					if (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS)
					{
						panel.update(System.currentTimeMillis());
						framesSkipped++;
						sleepTime += TIME_PER_FRAME;
					}
				//	storeStats();
				}
			}
			catch(Exception e)
			{
				
			}
		}
	}
	public void storeStats()
	{
		framesPerStatInterval++;
		intervalTimer += System.currentTimeMillis() - lastTime;
		lastTime = System.currentTimeMillis();
		if (intervalTimer > STAT_PERIOD)
		{
			double actualFPS = (double)(framesPerStatInterval / (intervalTimer / 1000));
			System.out.println(actualFPS);
			intervalTimer = 0;
			framesPerStatInterval = 0;
		}
	}

}
